package com.example.controller;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.easysdk.factory.Factory;
import com.example.entity.Order;
import com.example.mapper.OrderMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/alipay")
public class AliPayController {

    @Resource
    private OrderMapper orderMapper;

    private static final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
//    private static final String GATEWAY_URL ="https://openapi.alipay.com/gateway.do";

    private static final String FORMAT ="JSON";
    private static final String CHARSET ="utf-8";
    private static final String SIGN_TYPE ="RSA2";
    private static final String notifyUrl ="http://wbnd45.natappfree.cc/alipay/notify";
    private static final String appId ="9021000141695250";
    //应用私钥，就是工具生成的应用私钥
    private static final String appPrivateKey ="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCAafYTt5HNHZK+n/IVkByEOAuGAcgQw9rSU8Kadi03rWAB4AFwGM9I6F9ShS9nXgg3xpmDepnRG4LR7ca0sUxm8/+c9zB5EAW+UyPD2FL/To6W0bU/wsHhMl09xjY7vVPvTU++GSdbB+dAiuJX+GvtywfpP/GPnDyE77kyTrPVQHI/AkIr4YiUcp/0knDd7iv/GbR51WpYc2wsVU6nV2VHau4HJl8OCBvD6xScoBup790HWwjb9Vr5z0LcrGjJ6lSqtS5uRFEXCWhb6okHc28hkabQVTYKe5G8NYLFvtK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plVr/aFto0+WN5+HECgYAk5OuV3vst6jVf8rzgEJccUyhu/Vrq8DkYv+YgU771sd+SXhb5g9O5QGM81eqcgenZ/72Jw7h38GutJN7pMHT90jifgA1qqMI8uC6bh4VL5XZSx1Kbhi3VVLUyRYdTZWXmkw8fPU4TwgU71lnamJrHLJyUh2q9HSs3+hSLCU5n1Q==";
    // 支付宝公钥,对应APPID下的支付宝公钥。
    private static final String alipayPublicKey ="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp7kCFtjN1r3lnFq1hTeTKZMzdCKC075OosQPrYYjx6y9HtwHUdgu8Kg6GotryqBaZAPq5P/UYQu35zyeaZw4oEpoPj2vYli/WB/P6sJPKBqqHOy2IrlKg/qJTg7P8WBgx/130OirPjTblQXpVHIUIpb49ck7A3EC+nG8RP7HxUmWBRGnisu2+uK62POSXPdWjE3g2/i/HTsKYqYTD9Lwq6sLuf4X8aHZThTW7SndDPz8SzcCIkeeX5avwQmC2Egc9JECeEXN+y7pXCeB9q/TQiXYmGTVWW4cRD7tsYedKaCWDh3xfPzgYUZogPQ3L2o2UnyW9lFXf/vaMWmVq5y/lwIDAQAB";


    @GetMapping("/pay")
    public String  pay(String out_trade_no,String total_amount,String subject , HttpServletResponse httpResponse) throws Exception{
        System.out.println("交易名称: " + out_trade_no  );
        System.out.println("交易名称: "  + total_amount );
        System.out.println("交易名称: "   + subject);
        System.out.println("交易名称: =============================================================");

        String privateKey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCAafYTt5HNHZK+n/IVkByEOAuGAcgQw9rSU8Kadi03rWAB4AFwGM9I6F9ShS9nXgg3xpmDepnRG4LR7ca0sUxm8/+c9zB5EAW+UyPD2FL/To6W0bU/wsHhMl09xjY7vVPvTU++GSdbB+dAiuJX+GvtywfpP/GPnDyE77kyTrPVQHI/AkIr4YiUcp/0knDd7iv/GbR51WpYc2wsVU6nV2VHau4HJl8OCBvD6xScoBup790HWwjb9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P6q38aZNGULdFwfI3t2GlF18/F4brdi99TSlmYpm8T/B8OmiY/UleSYT5fgplVr/aFto0+WN5+HECgYAk5OuV3vst6jVf8rzgEJccUyhu/Vrq8DkYv+YgU771sd+SXhb5g9O5QGM81eqcgenZ/72Jw7h38GutJN7pMHT90jifgA1qqMI8uC6bh4VL5XZSx1Kbhi3VVLUyRYdTZWXmkw8fPU4TwgU71lnamJrHLJyUh2q9HSs3+hSLCU5n1Q==";
        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp7kCFtjN1r3lnFq1hTeTKZMzdCKC075OosQPrYYjx6y9HtwHUdgu8Kg6GotryqBaZAPq5P/UYQu35zyeaZw4oEpoPj2vYli/WB/P6sJPKBqqHOy2IrlKg/qJTg7P8WBgx/130OirPjTblQXpVHIUIpb49ck7A3EC+nG8RP7HxUmWBRGnisu2+uK62POSXPdWjE3g2/i/HTsKYqYTD9Lwq6sLuf4X8aHZThTW7SndDPz8SzcCIkeeX5avwQmC2Egc9JECeEXN+y7pXCeB9q/TQiXYmGTVWW4cRD7tsYedKaCWDh3xfPzgYUZogPQ3L2o2UnyW9lFXf/vaMWmVq5y/lwIDAQAB";


        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
        alipayConfig.setAppId("9021000141695250");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");

        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();

        model.setOutTradeNo(out_trade_no);
        model.setTotalAmount(total_amount);
        model.setSubject("Redmi K70 512GB");
        model.setProductCode("FAST_INSTANT_TRADE_PAY");

        request.setBizModel(model);
        request.setReturnUrl("http://localhost:7374/pay-success");
        request.setNotifyUrl(notifyUrl);
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "POST");
        // 如果需要返回GET请求，请使用
        // AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "GET");
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        return  pageRedirectionData;
    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                // 更新订单未已支付
                /**
                 Orders order = new Orders();
                 order.setId(Long.valueOf(tradeNo));
                 order.setStatus(2);
                 //                order.setCheckoutTime(params.get("gmt_payment"));
                 shopOrderMapper.updateById(order);**/
                int sun = extractNumber(params.get("out_trade_no"));
                Order order = new Order();
                order.setId(sun);
                order.setPaymentStatus(4);
                orderMapper.updateById(order);
            }
        }
        return "success";
    }

    public static int extractNumber(String input) {
        // 定义正则表达式，匹配 _数字_ 的形式
        String regex = "_(\\d+)_";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);

        // 查找匹配的数字
        if (matcher.find()) {
            // 提取匹配的数字并转换为整数
            return Integer.parseInt(matcher.group(1));
        } else {
            throw new IllegalArgumentException("输入字符串中没有匹配的数字");
        }
    }}
